import { defineStore } from 'pinia'
import request from '@/utils/request'
import { Profile } from '@/types/user'
import { ApiRes } from '@/types/data'
import { getProfile, setProfile, removeProfile } from '@/utils/storage'
import useStore from '@/store'

export default defineStore('user', {
  state() {
    return {
      // 个人信息
      profile: getProfile()
    }
  },
  actions: {
    // 根据用户名和密码登录
    async login(account: string, password: string) {
      const res = await request.post<ApiRes<Profile>>('/login', {
        account,
        password
      })
      this.profile = res.data.result
      setProfile(res.data.result)
      const { cart } = useStore()
      cart.mergeLocalCart()
    },
    // 根据手机号和验证码登录
    async mobileLogin(mobile: string, code: string) {
      const res = await request.post<ApiRes<Profile>>('/login/code', {
        mobile,
        code
      })
      this.profile = res.data.result
      setProfile(res.data.result)
      const { cart } = useStore()
      cart.mergeLocalCart()
    },
    // QQ登录
    async qqLogin(openId: string) {
      const res = await request.post<ApiRes<Profile>>('/login/social', {
        unionId: openId,
        source: 6
      })
      this.profile = res.data.result
      setProfile(res.data.result)
      const { cart } = useStore()
      cart.mergeLocalCart()
    },
    // 绑定qq登录
    async qqBindLogin(openId: string, mobile: string, code: string) {
      const res = await request.post<ApiRes<Profile>>('/login/social/bind', {
        unionId: openId,
        mobile,
        code
      })
      this.profile = res.data.result
      setProfile(res.data.result)
      const { cart } = useStore()
      cart.mergeLocalCart()
    },
    // 获取验证码
    async sendMobileCode(mobile: string) {
      await request.get('/login/code', {
        params: {
          mobile
        }
      })
    },
    // 获取绑定qq时的验证码
    async sendQQBindMsg(mobile: string) {
      await request.get('/login/social/code', {
        params: {
          mobile
        }
      })
    },
    // 绑定qq时获取验证码
    async sendQQPathMsg(mobile: string) {
      await request.get('/register/code', {
        params: {
          mobile
        }
      })
    },
    // 绑定qq时的绑定操作
    async qqPatchLogin(data: any) {
      const res = await request.post<ApiRes<Profile>>(
        `/login/social/${data.openId}/complement`,
        data
      )
      // 保存用户信息到state中
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    // 退出登录
    logout() {
      this.profile = {} as Profile
      removeProfile()
      const { cart } = useStore()
      cart.clearCart()
    }
  }
})